﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.Mvc;

using Lucene.Net.Documents;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Indexers.Lucene.Models
{
	public static class LuceneExtentions
	{
		public static T Get<T>(this Document doc, string name)
		{
			T result = default(T);
			if (name.IsNullOrTrimmedEmpty()
				|| doc == null)
			{
				return result;
			}
			var value = doc.Get(name);
			if (value == null)
			{
				return result;
			}
			var converter = TypeDescriptor.GetConverter(typeof(T));
			var cultureInfo = new System.Globalization.CultureInfo("en-US");
			if (converter != null)
			{
				try
				{
					result = (T)converter.ConvertFromString(null,cultureInfo, value);
				}
				catch(Exception ex)
				{
					var logger = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Logging.ILogger>();
					logger.Warn(ex.ToString());
				}
			}
			return result;
		}
	}
}
